<?php

namespace addons\kzvote\controller;

use addons\kzvote\library\Poster;
use addons\kzvote\library\Subscription;
use addons\kzvote\library\WechatSubscription;
use app\common\model\kzvote\Group;
use app\common\model\kzvote\Option;
use app\common\model\kzvote\Person;
use app\common\model\kzvote\Vote as VoteModel;
use think\Db;

/**
 * 投票接口
 */
class Vote extends Base
{
    protected $noNeedLogin = ['temp', 'index', 'poster','detail'];
    protected $noNeedRight = ['*'];

    /**
     * 模板列表
     */
    public function temp()
    {
        $model = new VoteModel;
        $list  = $model
            ->where(['status' => '10', 'check' => 1, 'is_temp' => 1])
            ->order('createtime desc')
            ->field('id, user_id, name, image, end_time,temp_name, createtime, person_count,count')
            ->select();
//        foreach ($list as &$row) {
//            $row['temp_image'] = request()->domain() . '/assets/kzvote/img/temp/' . $row['temp_name'] . '_img.png';
//        }
        $this->success('',$list);
    }

    /**
     * 投票列表
     */
    public function index()
    {
        $keyword = $this->request->param('keyword', '');
        $case = $this->request->param('case', '0');
        $model   = new VoteModel;
        $config  = kzvote_getConfig('active');
        if ((!isset($config['end_show']) || !$config['end_show'] || $config['end_show'] != 1) && $case != '1') {
            $model->where('end_time', '>', time());
        }
        if ($keyword) {
            $model->where('name', 'like', "%{$keyword}%");
        }
        if ($case == '1'){
            $model->where('case',$case);
        }
        $list = $model
            ->where(['status' => '10', 'check' => 1, 'is_temp' => 0, 'is_open' => 1])
            ->order('createtime desc')
            ->field('id, user_id, name, image, end_time,temp_name, createtime, person_count,count,mold')
            ->paginate(20, true);
        $this->success('',$list);
    }

    /**
     * 查询投票活动主数据
     */
    public function detail()
    {
        $vote_id = $this->request->param('vote_id');
        $detail  = VoteModel::get($vote_id);
        if ($detail) {
            $detail->append(['music','groups']);
            $detail->setInc('hit');
            if ($detail['option']) {
                $detail['option'] = explode(',', $detail['option']);
            }
            if ($detail['join_form']) {
                $detail['join_form'] = explode(',', $detail['join_form']);
            }
            if ($detail->mold == '3'){
                $person = Person::where('vote_id',$vote_id)->order('id asc')->field('id,vote_id,name,count')->select();
                $detail->person = $person;
            }else if ($detail->mold == '4'){
                $person = Person::where('vote_id',$vote_id)->order('id desc')->select();
                $detail->blue = $person[0]['name'];
                $detail->red = $person[1]['name'];
                $detail->person = $person;
            }
            if($detail->apply_check){
                $detail->apply_check_txt = '参赛报名审核已开启，请尽快提交待审核参赛作品图';
            }
        }
        $this->success('',$detail);
    }

    /**
     * 报名选项
     */
    public function option()
    {
        $list = (new Option)->column('name');
        $temp = [];
        if (count($list) < 3) {
            $temp[] = $list;
            $this->success('',$temp);
        }
        // 向上取整
        $argv = ceil(count($list) / 3);
        // 循环切片
        for ($i = 1; $i <= 3; $i++) {
            $temp[$i] = array_slice($list, $argv * ($i - 1), $argv);
        }
        $this->success('',$temp);
    }

    public function save()
    {
        $post            = $this->request->post();
        $post['desc'] = urldecode($post['desc']);
        $user = $this->auth->getUser();
        $post['user_id'] = $user['id'];
        // 判断后台是否设置了活动需要审核
        $config = kzvote_getConfig('active');
        if (isset($config['check']) && $config['check'] == 1) {
            $post['check'] = '0';
        } else {
            $post['check'] = '1';
        }
        if (isset($post['option']) && $post['option'] && is_array($post['option'])){
            $post['option'] = implode(',',$post['option']);
        }
        if ($post['end_time'] <= $post['start_time']){
            $this->error('活动结束时间不能小于开始时间');
        }

        unset($post['er_code']);
        if (isset($post['link']) && $post['link']){
            $post['link'] = json_encode($post['link']);
        }

        if (isset($post['id']) && $post['id']) {
            $model = VoteModel::get($post['id']);
        } else {
            unset($post['id']);
            $model = new VoteModel;
        }

        $model->allowField(true)->save($post);
        if (!$model->id) {
            $this->error('创建活动失败');
        }

        //文字投票的时候创建作品
        if ($model->mold == '3'){
            if (!isset($post['id'])){
                foreach ($post['person'] as $key=>$row){
                    $person[$key]['vote_id'] = $model->id;
                    $person[$key]['code'] = $key+1;
                    $person[$key]['name'] = $row['name'];
                    $person[$key]['status'] = '20';
                }
                (new Person())->saveAll($person);
            }else{
                $personModel = new Person();
                $person_ids = $personModel->where('vote_id',$model->id)->column('id');
                $new_person_ids = array_column($post['person'],'id');
                $remove_person_ids = array_diff($person_ids,$new_person_ids);
                $personModel->where('id','in',$remove_person_ids)->delete();
                foreach ($post['person'] as $key=>$row){
                    $post['person'][$key]['code'] = $key+1;
                }
                $personModel->allowField(true)->saveAll($post['person']);
            }
        }else if ($model->mold == '4'){
            //二选一pk
            if (!isset($post['id'])){
                $person = [
                    [
                        'vote_id' => $model->id,
                        'code' => 1,
                        'name' => $post['blue'],
                        'status' => '20',
                    ],
                    [
                        'vote_id' => $model->id,
                        'code' => 2,
                        'name' => $post['red'],
                        'status' => '20',
                    ]
                ];
                (new Person())->saveAll($person);
            }else{
                $person = Db::name('kzvote_person')->where('vote_id',$model->id)
                    ->order('id desc')
                    ->field('id,vote_id,name')->select();
                $person[0]['name'] = $post['blue'];
                $person[1]['name'] = $post['red'];
                (new Person())->saveAll($person);
            }
        }

        // 创建活动小程序码
        kzvote_qrCode($model,$model->id,'pages/vote/index');

        // 创建活动成功，发送订阅消息通知活动创建人
        // 发送订阅消息
        if (isset($post['send']) && $post['send']){
            if ($model['mold'] == '4'){
                $path = 'pages/vote/pk?vote_id=' . $model->id;
            }else if ($model['mold'] == '3'){
                $path = 'pages/vote/text?vote_id=' . $model->id;
            }else{
                $path = 'pages/vote/index?vote_id=' . $model->id;
            }
            $time = date('Y-m-d',$model['start_time']).'~'.date('Y-m-d',$model['end_time']);
            if ($this->platform == 'wxapp'){
                Subscription::vote_create(kzvote_getOpenid($model['user_id'],$this->platform),$path, $model['name'], $time);
            }elseif ($this->platform == 'wechat'){
                WechatSubscription::vote_create(kzvote_getOpenid($model['user_id'],$this->platform),$path, $model['name'], $time);
            }
        }

        $this->success('创建成功',['vote_id' => $model->id, 'temp_name' => $model['temp_name']]);

    }

    /**
     * 开启关闭活动,以及进行假删除
     */
    public function status()
    {
        $vote_id = $this->request->param('vote_id');
        $status  = $this->request->param('status');
        if (!$vote_id || !$status) {
            $this->error('缺少重要参数');
        }
        $res = (new VoteModel)->where('id', $vote_id)->update(['status' => $status]);
        if ($res) {
            $this->success('操作成功');
        }
        $this->error('操作失败');
    }

    /**
     * 查询与我有关的活动
     * 1.我创建的
     * 2.我参与的
     * 3.我报名的
     */
    public function active()
    {
        $type    = $this->request->param('type', 1);
        $user = $this->auth->getUser();
        $user_id = $user['id'];
        $model   = new VoteModel;
        if ($type == 1) {
            // 1.我创建的
            $data = $model->where(['user_id' => $user_id])->where('status', '<', '30')->order('id desc')->paginate(10);
        } else if ($type == 2) {
            // 2.我参与的
            $data = $model->alias('vote')
                ->join('kzvote_log log', 'log.vote_id = vote.id')
                ->distinct(true)
                ->where(['log.user_id' => $user_id])
                ->where('vote.status', '<', '30')
                ->field('vote.*')
                ->order('vote.id desc')
                ->paginate(10);
        } else {
            // 3.我报名的
            $data = $model->alias('vote')
                ->join('kzvote_person p', 'p.vote_id = vote.id')
                ->where('vote.status', '<', '30')
                ->where(['p.user_id' => $user_id])
                ->field('vote.*')
                ->order('vote.id desc')
                ->group('p.user_id')
                ->paginate(10);
        }

        $this->success('',$data);
    }

    /**
     * 添加分组
     */
    public function group()
    {
        $param = $this->request->param();
        $model = new Group();
        if (isset($param['type']) && $param['type'] == 'insert') {
            unset($param['id']);
            if ($model->allowField(true)->save($param)) {
                $this->success('添加成功');
            }
            $this->error('添加失败');
        } else if (isset($param['type']) && $param['type'] == 'update') {
            $model = Group::get($param['id']);
            if ($model->allowField(true)->save($param)) {
                $this->success('修改成功');
            }
            $this->error('修改失败');
        } else if (isset($param['type']) && $param['type'] == 'del') {
            $count = (new Person)->where('group_id', $param['id'])->count();
            if ($count) {
                $this->error('该分组下有作品，请先将作品移出');
            }
            if (Group::destroy($param['id'])) {
                $this->success('删除成功');
            }
            $this->error('删除失败');
        } else {
            $list = $model->where('vote_id', $param['vote_id'])->order('code desc')->select();
            $this->success('',$list);
        }
    }

    /**
     * 重新生成小程序码
     */
    public function erCode(){
        $vote_id  = $this->request->param('vote_id');
        $model = VoteModel::get($vote_id);
        if (!$model){
            $this->error('活动不存在');
        }
        $model->er_code = '';
        $model->save();
        // 创建活动小程序码
        $url = kzvote_qrCode($model,$model->id,'pages/vote/index');
        if ($url){
            $this->success('生成成功',['url' => $url]);
        }
        $this->error('生成失败');
    }
    /**
     * 生成活动海报
     */
    public function poster()
    {
        $vote_id  = $this->request->request('id');
        $bg_color = $this->request->param('bg_color', '#d84a41');
        $vote = VoteModel::get($vote_id);
        if($this->request->param('is_base', '0') == '0'){
            if (!$vote['er_code']) {
                // 小程序码不存在，重新生成
                $vote['er_code'] = kzvote_qrCode($vote, $vote_id, 'pages/vote/index');
            }
//        $user = $this->auth->getUser();

            $img   = [];
//        $img[] = [
//            'url'     => cdnurl($user['avatar'], true), // 头像
//            'is_yuan' => true, // true图片圆形处理
//            'stream'  => 0,
//            'left'    => -1, // 小于0为小平居中
//            'top'     => 30,
//            'right'   => 0,
//            'width'   => 112, // 图像宽
//            'height'  => 112, // 图像高
//            'opacity' => 100, // 透明度
//        ];
            $img[] = [
                'url'     => cdnurl($vote['image'], true),
                'is_yuan' => false, // true图片圆形处理
                'stream'  => 0,
                'left'    => -1, // 小于0为小平居中
                'top'     => 30,
                'right'   => 0,
                'width'   => 540, // 图像宽
                'height'  => 400, // 图像高
                'opacity' => 100, // 透明度
                'name'    => 'vote',
            ];
            $img[] = [
                'url'     => $vote['er_code'],
                'is_yuan' => false, // true图片圆形处理
                'stream'  => 0,
                'left'    => -1, // 小于0为小平居中
                'top'     => 605,
                'right'   => 0,
                'width'   => 250, // 图像宽
                'height'  => 250, // 图像高
                'opacity' => 100, // 透明度
                'name'    => 'er_code'
            ];

            $txt   = [];
//        $txt[] = [
//            'text'      => $user['nickname'], // 昵称
//            'left'      => -1, // 小于0为小平居中
//            'top'       => $img[0]['top'] + 160,
//            'fontSize'  => 18, // 字号
//            'fontColor' => '255,255,255', // 字体颜色
//            'angle'     => 0,
//        ];
//        $txt[] = [
//            'text'      => '邀请您参加投票活动',
//            'left'      => -1, // 小于0为小平居中
//            'top'       => $img[0]['top'] + 200,
//            'fontSize'  => 22, // 字号
//            'fontColor' => '255,255,255', // 字体颜色
//            'angle'     => 0,
//        ];

            // 字符过长，换行
            if (strlen($vote['name']) > 48) {
                $name1 = substr($vote['name'], 0, 45);
                $txt[] = [
                    'text'      => $name1 . ' ...',
                    'left'      => -1, // 小于0为小平居中
                    'top'       => 480,
                    'fontSize'  => 22, // 字号
                    'fontColor' => '255,255,255', // 字体颜色
                    'angle'     => 0,
                ];

//            $name2 = substr($vote['name'], 48);
//            $txt[] = [
//                'text'      => $name2,
//                'left'      => -1, // 小于0为小平居中
//                'top'       => $img[count($img) - 1]['top'] - 40,
//                'fontSize'  => 20, // 字号
//                'fontColor' => '255,255,255', // 字体颜色
//                'angle'     => 0,
//            ];
            } else {
                $txt[] = [
                    'text'      => $vote['name'],
                    'left'      => -1, // 小于0为小平居中
                    'top'       => 480,
                    'fontSize'  => 22, // 字号
                    'fontColor' => '255,255,255', // 字体颜色
                    'angle'     => 0,
                ];
            }

            $txt[] = [
                'text'      => '投票时间: '.date('Y-m-d',$vote['start_time']).' ~ '.date('Y-m-d',$vote['end_time']), // 文字内容
                'left'      => -1, // 小于0为小平居中
                'top'       => 530,
                'fontSize'  => 18, // 字号
                'fontColor' => '255,255,255', // 字体颜色
                'angle'     => 0,
            ];

            $txt[] = [
                'text'      => '长按或扫码识别参加', // 文字内容
                'left'      => -1, // 小于0为小平居中
                'top'       => $img[count($img) - 1]['top'] + 350,
                'fontSize'  => 18, // 字号
                'fontColor' => '255,255,255', // 字体颜色
                'angle'     => 0,
            ];
//        $txt[] = [
//            'text'      => '我发起一个投票活动,快来加入我吧', // 文字内容
//            'left'      => -1, // 小于0为小平居中
//            'top'       => $img[count($img) - 1]['top'] + 420,
//            'fontSize'  => 18, // 字号
//            'fontColor' => '255,255,255', // 字体颜色
//            'angle'     => 0,
//        ];

            $config = array(
                'image' => $img,
                'text'  => $txt,
            );

            // 背景颜色代码转RGB
            $rgba = kzvote_hex2rgba($bg_color, false, true);
//        list($r, $g, $b) = sscanf($color, "#%02x%02x%02x");
//        $output = 'rgb(' . $r . ',' . $g . ',' . $b . ')';
            echo Poster::createPoster($config, '', $rgba);
        }else{
            // 二维码目录创建-S
            $voteDir = ROOT_PATH . 'public' . DS . 'vote' . DS . $vote_id;
            $cdnVoteQrcode = $this->request->domain(). DS . 'vote' . DS . $vote_id. DS ."vote.png";
            $voteQrcode = $voteDir. DS ."vote.png";
            if(!is_dir($voteDir)){
                createsysdir($voteDir);
            }
            // 二维码目录创建-E
            // 生成二维码-S
            if(!file_exists($voteQrcode)) {
                $params = [
                    'text' => url("/vote", "", false, true)."/#/pages/vote/index?vote_id=".$vote_id,
                    'size' => '300',
                    'padding' => '15',
                    'errorlevel' => 'medium',
                    'foreground' => '#000000',
                    'background' => '#ffffff',
                    'logo' => '1',
                    'logosize' => '50',
                    'label' => '',
                    'labelmargin' => '0',
                    'labelfontsize' => '14',
                    'labelalignment' => 'center',
                    'labelfontcolor' => '#000000'
                ];
                $qrCode = \addons\qrcode\library\Service::qrcode($params);
                $qrCode->saveToFile($voteQrcode);
            }
            // 生成二维码-E
            if($vote["poster"]){
                $posterImgInfo = \app\common\model\Attachment::get(["url"=>$vote["poster"]]);
                list($left, $top) = explode(",", $vote["poster_qr_pos"]);
                $config = array();
                $img[] = [
                    'url'     => cdnurl($vote["poster"], true),
                    'stream'  => 0,
                    'left'    => 0, // 小于0为小平居中
                    'top'     => 0,
                    'width'   => $posterImgInfo->imagewidth, // 图像宽
                    'height'  => $posterImgInfo->imageheight, // 图像高
                    'opacity' => 100, // 透明度
                    'name'    => 'poster_bg'
                ];
                $config['size'] = [
                    'width'   => $posterImgInfo->imagewidth, // 图像宽
                    'height'  => $posterImgInfo->imageheight, // 图像高
                ];
                $img[] = [
                    'url'     => $cdnVoteQrcode,
                    'stream'  => 0,
                    'left'    => $left, // 小于0为小平居中
                    'top'     => $top,
                    'width'   => intval($vote["poster_qr_size"]), // 图像宽
                    'height'  => intval($vote["poster_qr_size"]), // 图像高
                    'opacity' => 100, // 透明度
                    'name'    => 'poster_bg'
                ];
                $config['image'] = $img;
                $config['text'] = [];
                // 背景颜色代码转RGB
                $rgba = kzvote_hex2rgba($bg_color, false, true);
                $content = Poster::createQrPoster($config, '', $rgba);
                return response($content, 200, ['Content-type' => "image/png" ]);
            }else{
                echo "获取配置错误";
            }
        }
    }
}
